'use strict';

var Model = require('../../config/models').userModel,
  hmac = require('../../lib/hmac');
var service = module.exports = {};

service.create = function(entity) {
  return Model.create(entity);
};

service.find = function(conditions, projection, options) {
  return Model.find(conditions, projection, options).exec();
};

service.remove = function(conditions) {
  return Model.remove(conditions );
};

service.update = function(conditions, update, options) {
  return Model.update(conditions, update, options).exec();
};

service.findById = function(id, projection, options) {
  return Model.findById(id, projection, options).exec();
};

service.findOne = function(conditions, projection, options) {
  return Model.findOne(conditions, projection, options).exec();
};

service.findByIdAndUpdate = function(id, update, options) {
  return Model.findByIdAndUpdate(id, update, options).exec();
};

service.findByIdAndRemove = function(id, options) {
  return Model.findByIdAndRemove(id, options).exec();
};

service.findByUserName = function(userName) {
  return this.findOne(userName, '-passWord');
};

service.checkUserLogin = function(query) {
  return Model.findOne(query, '-passWord').populate({path: 'roleId', select: {_id: 1, name: 1}}).exec();
};

service.updateAccessToken = function(conditions, token) {
  return this.update(conditions, {$set: {accessToken: token}});
};

service.createUser = function(entity) {
  entity.passWord = hmac.sha1Encrypt(entity.passWord);
  return this.create(entity);
};

service.changePw = function(id, oldPw, newPw) {
  oldPw = hmac.sha1Encrypt(oldPw);
  newPw = hmac.sha1Encrypt(newPw);
  return this.update({_id: id, passWord: oldPw}, {passWord: newPw});
};

service.findUserList = function(conditions) {
  return this.find(conditions, '-passWord');
};

service.findUserById = function(conditions) {
  return this.find(conditions, '-passWord');
};

service.findUserByOpenId = function(conditions) {
  if (typeof conditions !== 'object') {
    conditions = {
      openId: conditions
    };
  }
  return this.find(conditions, '-passWord');
};

service.isNeedUpdateWechatInfo = function(user) {
};

service.updateWechatInfo = function(user, userInfo) {
};
